<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/2/27
 * Time: 14:40
 */
namespace app\mobile\controller;

use app\common\model\Ppintuan;
use think\lang;
use think\Model;
use think\Db;
use app\home\controller\Buy;
use app\common\model\Address;

class PintuanOld extends MobileMall {

    public function _initialize(){
        parent::_initialize();
        Lang::load(APP_PATH . 'mobile\lang\zh-cn\pintuan_list lang.php');
    }

    public function index()
    {
        // 当前页数(框架自动判断)
        $page = intval(input("get.page")) ? intval(input("get.page")) : 1;
        // 每页条数
        $page_nums = intval(input("get.page_nums")) ? intval(input("get.page_nums")) : 10;
        $goods_list = model('ppintuan')->getPintuanGoodDataList(["pintuan_state"=>1],$page_nums,'pintuan_end_time asc','p.*,g.goods_price');
        //$goods_list = Db::table('sc_ppintuan')->where('pintuan_state','1')->select();
        $goods_list = $goods_list->toArray();

        $goods_list_sort = $goods_list;
        unset($goods_list_sort["data"]);
        foreach ($goods_list["data"] as $k => $v){
            // 计算折扣之后的价格
            $v["last_price"] = bcmul(bcdiv($v["pintuan_zhe"],10,2),$v["goods_price"],2);
            $goods_list_sort["data"][] = $v;
        }

        output_data($goods_list_sort);
    }


    // 获取拼团商品信息
    public function pintuanGoodsInfo(){
        $collage_id = intval(input("post.collage_id"));
        if(empty($collage_id)){
            output_data(["error"=>"缺少参数"]);
        }
        // 拼团商品信息
        $pt_goods_detail = model("ppintuan")->getPintuanGoodsInfo(["pintuan_id"=>$collage_id,"pintuan_state"=>1],"p.*,gc.goods_commonid,gc.goods_name,gc.gc_name,gc.goods_price,gc.goods_marketprice,gc.goods_image,gc.goods_freight,gc.goods_state");
        if(!$pt_goods_detail){
            output_data(["error"=>"活动不存在"]);
        }
        if($pt_goods_detail["goods_state"]!=1){
            output_data(["error"=>"该商品已下架"]);
        }
        // 图片处理
        $pt_goods_detail["pintuan_image"] = goods_cthumb($pt_goods_detail["pintuan_image"]);

        // 商品详细信息
        $pt_goods_detail_info = model("ppintuan")->getPintuanGoodsDeatilInfo(["gc.goods_commonid"=>$pt_goods_detail["goods_commonid"]],"g.goods_id,g.goods_name,g.goods_price,g.goods_marketprice,g.goods_image,g.goods_click,g.goods_salenum,g.goods_collect,g.goods_freight");
        $url = $_SERVER['SERVER_NAME']."/mobile/goods/goods_detail?goods_id=".$pt_goods_detail_info[0]["goods_id"];
        $res_data = json_decode(http_request($url),true);

        $goods_attr = [];
        foreach ($res_data["result"]["goods_detail"]["goods_info"]["goods_attr"] as $k => $v){
            $goods_attr[] = $v["name"];
        }
        $res_data["result"]["goods_detail"]["goods_info"]["goods_attr"] = $goods_attr;

        $pt_goods_detail["goods_detail"] = $res_data["result"]["goods_detail"];
        $pt_goods_detail["goods_image"] = goods_cthumb($pt_goods_detail["goods_image"],240);

        // 拼团记录
        $ppintuangroup_model = model('ppintuangroup');
        $ppintuanorder_model = model('ppintuanorder');
        $ppintuangroup_list = $ppintuangroup_model->getPpintuangroupList(["pintuan_id"=>$collage_id], 10); #获取开团信息
        foreach ($ppintuangroup_list as $key => $ppintuangroup) {
            //获取开团订单下的参团订单
            $condition = array();
            $condition["pintuan_id"] = $collage_id;
            $condition['pintuangroup_id'] = $ppintuangroup['pintuangroup_id'];
            $ppintuangroup_list[$key]['order_list'] = $ppintuanorder_model->getPpintuanorderList($condition);
        }

        $pt_goods_detail["record"] = $ppintuangroup_list;
        output_data($pt_goods_detail);
    }



    // 获取拼团商品信息
    public function pintuanGoodsDetailInfo(){
        $collage_id = intval(input("post.collage_id"));
        if(empty($collage_id)){
            output_data(["error"=>"缺少参数"]);
        }
        $pt_goods_detail = model("ppintuan")->getPintuanGoodsInfo(["pintuan_id"=>$collage_id,"pintuan_state"=>1],"gc.goods_commonid,gc.goods_name,gc.gc_name,gc.goods_price,gc.goods_marketprice,gc.goods_image,gc.goods_freight,goods_state");
        if(!$pt_goods_detail){
            output_data(["error"=>"活动不存在"]);
        }

        if($pt_goods_detail["goods_state"]!=1){
            output_data(["error"=>"该商品已下架"]);
        }

        $pt_goods_detail_info = model("ppintuan")->getPintuanGoodsDeatilInfo(["gc.goods_commonid"=>$pt_goods_detail["goods_commonid"]],"g.goods_id,g.goods_name,g.goods_price,g.goods_marketprice,g.goods_image,g.goods_click,g.goods_salenum,g.goods_collect,g.goods_freight");
        $pt_goods_detail_sort = [];
        foreach ($pt_goods_detail_info as $k => $v){
            $v["goods_image"] = goods_cthumb($v["goods_image"],240);
            $pt_goods_detail_sort[] = $v;
        }
        output_data($pt_goods_detail_sort);
    }


    protected function getDeliveryTypeByCartId($cart_id)
    {
        $cart = db('cart' )->where([
            'cart_id' => $cart_id
        ])->find();
        $goods = \app\common\model\Goods::get($cart['goods_id']);
        return $goods['trade_mode'];
    }
    protected function getDeliveryTypeByGoodsId($goods_id) {
        $goods = \app\common\model\Goods::get($goods_id);
        return $goods['trade_mode'];
    }


    // buy_step1
    public function buy_step1(){
        if(empty(input('post.'))){
            $this->error(lang('param_error'));
        }
        //虚拟商品购买分流
        // $this->_buy_branch(input('post.'));

        $ifcart = input('post.ifcart');
        $cart_id[] = input('post.cart_id');
        $pintuan_id = input("pintuan_id");
        $pintuangroup_id = input("pintuangroup_id");

        $buy_logic = model('buy','logic');
        $result = $buy_logic->buyStep1($cart_id, $ifcart, $this->member_info["member_id"],["pintuan_id"=>$pintuan_id,"pintuangroup_id"=>$pintuangroup_id]);

        if ($result['code'] != 'SUCCESS') {
            output_data(["error"=>$result['msg']]);
        } else {
            $result = $result['data'];
        }
        //根据商品类型进行分组处理
        $trade_group = [];
//        $tmp_amount = 0;
        foreach ($result['cart_list'] as $key => $item){
//            $result['cart_list'][$key]['declare_num_total'] = sc_price_format($item['declare_num']);
//            $tmp_amount += $result['cart_list'][$key]['declare_num_total'];
            isset($trade_group[$item['trade_mode']]) or $trade_group[$item['trade_mode']] = [
                'trade_mode' => $item['trade_mode'],
                'goods_info' => [],
                'trade_mode_format' => config('trade_mode.'.$item['trade_mode']),
                'total_price' => 0,
                'total' => 0,
                'tax' => 0,
                'total_tax' => 0,
                'total_tax_amount' => 0,
            ];
            $trade_group[$item['trade_mode']]['goods_info'][] = $item;
            $trade_group[$item['trade_mode']]['total_price'] += $item['goods_price'] * $item['goods_num'];

            $trade_group[$item['trade_mode']]['total'] += $item['goods_num'];
            //税额和总税额
            if(isset($item['tax_rate'])){
                $trade_group[$item['trade_mode']]['tax'] = $item['tax_rate']/100 * $item['goods_price'] * $item['goods_num'];
                $trade_group[$item['trade_mode']]['total_tax'] += $trade_group[$item['trade_mode']]['tax'];
            }
        }
        $result['cart_list'] = $trade_group;
        output_data($result);
    }



    public function change_addr() {
        $buy_logic = model('buy','logic');

        if(empty(input('post.freight_hash')) || empty(input('post.city_id')) || empty(input('post.area_id'))){
            output_data(["error"=>"信息不全"]);
        }
        $data = $buy_logic->changeAddr(input('post.freight_hash'), input('post.city_id'), input('post.area_id'), $this->member_info["member_id"]);
        if (!empty($data)) {
            output_data($data);
        } else {
            output_data(["error"=>"信息为空"]);
        }
    }


    //buy_step2
    public function buy_step2(){
        $buy_logic = model('buy','logic');
        // $member_type = $this->member_info['member_type'];
        // 来源于购物车标志
        $ifcart = input('post.ifcart');
        $cart_list = input('post.');
        $cart_list["order_from"] = 2;

        if(empty($cart_list["cart_id"]) || empty($cart_list["pay_name"]) || empty($cart_list["address_id"]) || empty($cart_list["buy_city_id"]) || empty($cart_list["offpay_hash"]) || empty($cart_list["offpay_hash_batch"])){
            output_data(["error"=>"信息不全"]);
        }

        $cart_list["pay_message"] = empty($cart_list["pay_message"]) ? "" : $cart_list["pay_message"];
        $cart_list["voucher"] = empty($cart_list["voucher"]) ? "" : $cart_list["voucher"];
        $cart_list["ifcart"] = empty($cart_list["voucher"]) ? "" : $cart_list["ifcart"];
        $cart_list["pintuan_id"] = empty($cart_list["pintuan_id"]) ? "" : $cart_list["pintuan_id"];
        $cart_list["pintuangroup_id"] = empty($cart_list["pintuangroup_id"]) ? 0 : $cart_list["pintuangroup_id"];


        // 需要的参数
        // ifcart                    是否购物车
        // cart_id                   商品ID|商品数量 26|3
        // pay_message               买家留言
        // voucher                   代金券
        // order_from                订单来源1pc 2手机
        // pay_name                  offline/online
        // vat_hash                  是否保存增值税发票判断标志
        // address_id                收货地址


        // buy_city_id               城市ID
        // allow_offpay
        // allow_offpay_batch        freight_hash:1中返回的freight_list去请求change_addr接口
        // offpay_hash
        // offpay_hash_batch


        // invoice_id                邀请人

        $group = [];
        $need_valid = false;
        $cart_id_str = $cart_list["cart_id"];
        $pay_message_str = $cart_list["pay_message"];
        $voucher_str = $cart_list["voucher"];
        unset($cart_list["cart_id"]);
        unset($cart_list["pay_message"]);
        unset($cart_list["voucher"]);
        $cart_list["cart_id"][] = $cart_id_str;
        $cart_list["pay_message"][] = $pay_message_str;
        $cart_list["voucher"][] = $voucher_str;

        foreach($cart_list['cart_id'] as $item) {
            $_data = explode('|', $item);
            if($ifcart == false){
                $trade_mode = $this->getDeliveryTypeByGoodsId($_data[0]);
            }else{
                $trade_mode = $this->getDeliveryTypeByCartId($_data[0]);
            }
            //$trade_mode_format  = config('trade_mode.'.$trade_mode);
            $group[$trade_mode][] = $item;
            if($trade_mode > TRADE_NORMAL) $need_valid = true;
        }
        $address_id = input('post.address_id');
        $address = Address::get($address_id);
        if($need_valid && !$address['real_name']) {
            output_data(["error"=>"收货地址，必须提交实名信息"]);
        }

        $order_list = [];
        foreach ($group as $val){
            $cart_list['cart_id']= $val;
            $result = $buy_logic->buyStep2($cart_list, $this->member_info["member_id"], $this->member_info["member_name"], $this->member_info["member_email"]);
            if (!$result['code']) {
                output_data(["error"=>$result['msg']]);
            }
            $order_list[]= ['pay_sn' => $result['data']['pay_sn']];
        }

        if(count($order_list) >1){
            //订单数大于1转向订单列表
            output_data(["error"=>"订单创建成功，到订单中心去支付"]);
        }
        output_data($order_list);

    }



    // 获取支付方式列表
    public function pay_list() {
        $pay_sn = input('param.pay_sn');
        if (!preg_match('/^\d{20}$/', $pay_sn)) {
            output_data(["error"=>"该订单不存在"]);
        }

        //查询支付单信息
        $order_model = model('order');
        $pay_info = $order_model->getOrderpayInfo(array('pay_sn' => $pay_sn, 'buyer_id' => $this->member_info["member_id"]), true);
        if (empty($pay_info)) {
            output_data(["error"=>"该订单不存在"]);
        }

        //取子订单列表
        $condition = array();
        $condition['pay_sn'] = $pay_sn;
        $condition['order_state'] = array('in', array_values(array(ORDER_STATE_NEW, ORDER_STATE_PAY)));
        $order_list = $order_model->getOrderList($condition, '', 'order_id,order_state,payment_code,order_amount,rcb_amount,pd_amount,order_sn', '', '', array(), true);

        if (empty($order_list)) {
            output_data(["error"=>"未找到需要支付的订单"]);
        }

        //重新计算在线支付金额
        $pay_amount_online = 0;
        $pay_amount_offline = 0;
        //订单总支付金额(不包含货到付款)
        $pay_amount = 0;

        foreach ($order_list as $key => $order_info) {

            $payed_amount = floatval($order_info['rcb_amount']) + floatval($order_info['pd_amount']);
            //计算相关支付金额
            if ($order_info['payment_code'] != 'offline') {
                // 已产生但未支付
                if ($order_info['order_state'] == ORDER_STATE_NEW) {
                    $pay_amount_online += sc_price_format(floatval($order_info['order_amount']) - $payed_amount);
                }
                $pay_amount += floatval($order_info['order_amount']);
            } else {
                $pay_amount_offline += floatval($order_info['order_amount']);
            }

            //     //显示支付方式与支付结果
            //     if ($order_info['payment_code'] == 'offline') {
            //         $order_list[$key]['payment_state'] = "货到付款";
            //     } else {
            //         $order_list[$key]['payment_state'] = "在线支付";
            //         if ($payed_amount > 0) {
            //             $payed_tips = '';
            //             if (floatval($order_info['rcb_amount']) > 0) {
            //                 $payed_tips = "充值卡已支付".'：￥' . $order_info['rcb_amount'];
            //             }
            //             if (floatval($order_info['pd_amount']) > 0) {
            //                 $payed_tips .= "预存款已支付".'：￥' . $order_info['pd_amount'];
            //             }
            //             $order_list[$key]['order_amount'] .= " ( {$payed_tips} )";
            //         }
            //     }
        }

        //如果线上线下支付金额都为0，转到支付成功页
        if (empty($pay_amount_online) && empty($pay_amount_offline)) {
            output_data(['pay_sn' => $pay_sn, 'pay_amount' => sc_price_format($pay_amount)]);
        }

        //输出订单描述暂时没有符合条件的支付方式，请 联系卖家 进行后续购买流
        if (empty($pay_amount_online)) {
            $order_remind = "下单成功，我们会尽快为您发货，请保持电话畅通！";
        } elseif (empty($pay_amount_offline)) {
            $order_remind = "请您及时付款，以便订单尽快处理！";
        } else {
            $order_remind = "部分商品需要在线支付，请尽快付款！";
        }

        //显示支付接口列表
        if ($pay_amount_online > 0) {
            $payment_model = model('payment');
            $condition = array();
            $condition['payment_platform'] = 'app';
            $payment_list = $payment_model->getPaymentOpenList($condition);
            if(empty($payment_list)){
                output_data(["error"=>"暂未找到合适的支付方式"]);
            }
            foreach ($payment_list as $key => $payment) {
                if(in_array($payment['payment_code'], array('predeposit','offline'))){
                    unset($payment_list[$key]);
                }
            }
        }

        output_data($payment_list);
    }



    // 拼团开团表
    public function pintuan_group(){
        $pintuan_id = input("get.pintuan_id");
        if(empty($pintuan_id)){
            output_data(["error"=>"信息不全"]);
        }
        // 当前页数(框架自动判断)
        $page = intval(input("get.page")) ? intval(input("get.page")) : 1;
        // 每页条数
        $page_nums = intval(input("get.page_nums")) ? intval(input("get.page_nums")) : 10;

        $list = model("Ppintuangroup")->getPpintuangroupList(["pintuan_id"=>$pintuan_id],$page_nums);
        $res = model("Ppintuangroup")->page_info->toArray();

        $res_list["total"] =  $res["total"];
        $res_list["per_page"] =  $res["per_page"];
        $res_list["current_page"] =  $res["current_page"];
        $res_list["last_page"] =  $res["last_page"];
        $res_list["data"] = $list;

        output_data($res_list);
    }


    /**
     * 得到所购买的id和数量
     *
     */
    private function _parseItems($cart_id) {
        //存放所购商品ID和数量组成的键值对
        $buy_items = array();
        if (is_array($cart_id)) {
            foreach ($cart_id as $value) {
                if (preg_match_all('/^(\d{1,10})\|(\d{1,6})$/', $value, $match)) {
                    $buy_items[$match[1][0]] = $match[2][0];
                }
            }
        }
        return $buy_items;
    }


    /**
     * 购买分流
     */
    private function _buy_branch($post) {
        if (!isset($post['ifcart'])) {
            //取得购买商品信息
            $buy_items = $this->_parseItems($post['cart_id']);
            $goods_id = key($buy_items);
            $quantity = current($buy_items);

            $goods_info = model('goods')->getGoodsOnlineInfoAndPromotionById($goods_id);
            if ($goods_info['is_virtual']) {
                $this->redirect('Buyvirtual/buy_step1',['goods_id'=>$goods_id,'quantity'=>$quantity]);
            }
        }
    }

}
